<?php

namespace app\common\model;

use think\facade\Cookie;
use think\facade\Session;
use think\Model;

class User extends Model
{
    protected $pk = 'id';
    protected $table = 't_user';

    /**
     * 检查用户登陆 通过用户名密码
     *
     * @param string $name 用户名
     * @param string $pwd 密码
     * @return void
     */
    public function checkUserinfo($name = '', $pwd = '')
    {
        if (empty($name) || empty($pwd)) {
            return false;
        }

        $userInfo = self::where('username', $name)->find();
        if (!password_verify((string)$pwd, $userInfo['password'])) {
            return false;
        } else {
            return $userInfo;
        }
    }

    /**
     * 检查用户登陆 通过cookie获的用户名密码
     *
     * @param string $name 用户名
     * @param string $pwd 密码
     * @return void
     */
    public function checkUserinfoByCookie($name = '', $pwd = '')
    {
        if (empty($name) || empty($pwd)) {
            return false;
        }

        $userInfo = self::where('username', $name)->where('password', $pwd)->find();
        if (null === $userInfo) {
            return false;
        } else {
            return $userInfo;
        }
    }

    /**
     * 写入uuid
     *
     * @param object $userObject 用户对象实例
     * @param string $uuid  用户uuid
     * @return void
     */
    public function writeUuid($userObject, $uuid = '')
    {
        if (!is_object($userObject) || $uuid == '') {
            return false;
        }
    }

    /**
     * 密码加密
     *
     * @param string $pwd 密码
     * @return void
     */
    public function encryPassword($pwd = '')
    {
        if (empty($pwd)) {
            return false;
        }

        return md5(sha1($pwd));
    }

    /**
     * 通过token获取用户信息
     *
     * @param string $token
     *
     * @return void
     */
    public static function getUserinfoByToken($token = '')
    {
        $userinfo = self::where('uuid', $token)->find();
        if (!$userinfo) {
            return false;
        }

        //比较时间戳
        if (time() > strtotime($userinfo['token_expire_time'])) {
            return false;
        }

        return $userinfo;
    }

    /**
     * 获取uuid
     *
     * @return void
     */
    public static function getUuid()
    {
        return password_hash(mt_rand(0, 10000), PASSWORD_DEFAULT);
    }

    /**
     * 清除用户信息，cookie和session
     *
     * @return void
     */
    public static function clearUserinfo()
    {
        Session::delete('userinfo');
        Session::clear();
        Cookie::delete('userinfo');
    }


    public static function checkOnlyLogin($sessionUserInfo='')
    {
        if(empty($sessionUserInfo)) return false;
        $userinfo = self::find($sessionUserInfo->id);
        if ($userinfo->uuid !== $sessionUserInfo['uuid']) {
            return false;
        }
        return true;
    }

    public static function getList($type = 1, $page = 1, $limit = 10)
    {
        $data = self::where('is_deleted', 0);
        //用户列表
        // if($type == 2){
        //     $message->where('status', 1);
        // }

        $dataCount = $data->count(); //计算总数

        $data = $data->page($page, $limit)->order('id', 'desc')->select();

        // foreach ($message as $key => $value) {
        //     $message[$key]['status_text'] = $value->status_text;
        // }

        if ($data) {
            return ['count' => $dataCount, 'res' => $data];
        }

        return ['count' => 0, 'res' => null];

    }

    /**
     * 创建用户
     *
     * @param array $userData
     * @return void
     */
    public function createUser($userData = [])
    {
        if (empty($userData)) {
            return false;
        }

        $userData['password'] = self::encryPassword('abcd1234');
        $userData['create_time'] = getCurrentDateTime();
        $userData['update_time'] = getCurrentDateTime();
        $res = self::allowField(true)->save($userData);
        return $res;
    }

    /**
     * 检查数据唯一性
     *
     * @param array $data 传入 字段名 => 值  键值对
     * @return void
     */
    public static function checkDataUniqueness($data = [])
    {
        if ($data) {
            $user = self::order('id', 'desc');
            foreach ($data as $k => $v) {
                $user->whereOr($k, $v);
            }
            $res = $user->find();
            if ($res) {
                return false;
            } else {
                return true;
            }

        } else {
            return false;
        }
    }

    /**
     * 删除用户
     *
     * @param string|array $id
     * @return bool|int
     */
    public static function deleteUser($id = 0)
    {
        if($id < 0){
            return false;
        }
        $data = self::where('id', $id)->update(['is_deleted' => 1]);
        return $data;
    }

    /**
     * 转换性别显示
     *
     * @param [type] $value
     * @return void
     */
    public function getGenderAttr($value)
    {
        $gender = [0 => '未定义', 1 => '男', 2 => '女'];
        return $gender[$value];
    }

    /**
     * 更新字段
     *
     * @param array $updateData
     * @return void
     */
    public function updateField($id = 0, $updateData = [])
    {
        if (empty($updateData) || $id < 1) {
            return false;
        }

        $data = self::where('id', $id)->update($updateData);
        return $data;
    }

    /**
     * 更改状态
     *
     * @return void
     */
    public static function changeStatus($id = 0)
    {
        if ($id < 1) {
            return false;
        }

        $data = self::find($id);
        if(!$data) return false;
        $data->status == 0 ? $data->status = 1 : $data->status = 0;
        if(false === $data->save()) return false;
        return $data;

    }
}
